package com.lzp.java.concurrent.threadcore.stopthread;

/**
 * 子方法通常在方法签名中抛出异常，然后在run方法中处理
 *
 * @author lzp
 * @date 2020/01/31
 */
public class RightWayStopThreadInProduct implements Runnable {
    @Override
    public void run() {
        while (true && !Thread.currentThread().isInterrupted()) {
            System.out.println("stop");
            try {
                subTask();
            } catch (InterruptedException e) {
                // 恢复中断，退出循环
                Thread.currentThread().interrupt();
                System.out.println("打印日志，输出栈轨迹");
                e.printStackTrace();
            }
        }
    }

    private void subTask() throws InterruptedException {
        Thread.sleep(1000);
    }

    // /**
    //  * 不好的示范
    //  */
    // private void subTask() {
    //     try {
    //         Thread.sleep(5000);
    //     } catch (InterruptedException e) {
    //         e.printStackTrace();
    //     }
    // }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadInProduct());
        thread.start();
        Thread.sleep(500);
        thread.interrupt();
    }
}
